import { Button, Cascader, Form, Input } from "antd-mobile";
import type { Address } from "./AddressList";
import { useEffect, useRef, useState } from "react";
import cascaderOptions, { type CascaderOption } from "@pansy/china-division";
interface AddressFormProps {
  data: Address | null;
  onSave: (addr: Address) => void;
  onCancel: () => void;
}
type Items = CascaderOption[];
export default function AddressForm(props: AddressFormProps) {
  const { data, onSave, onCancel } = props;
  const [form] = Form.useForm();
  const [visible, setVisible] = useState(false);
  const onFinish = (values: Address) => {
    if (data && data.id) {
      onSave({ ...data, ...values, ...addresRef.current });
    } else {
      onSave({ ...values, ...addresRef.current });
    }
  };
  useEffect(() => {
    form.setFieldsValue(data);
  }, [data]);
  const addresRef = useRef({});
  const handleConfirm = (val: string[], items: Items) => {
    const addressValue = items.map((v) => v.label).join("");
    addresRef.current = {
      addressCode: val,
      address: addressValue,
    };
    form.setFieldValue("address", addressValue);
  };
  return (
    <div className="fixed top-0 left-0 h-full w-full bg-white z-50 p-4">
      <h3 className="text-lg font-bold mb-4">
        {data ? "编辑地址" : "新增地址"}
      </h3>
      <Form
        onFinish={onFinish}
        form={form}
        layout="horizontal"
        footer={
          <div className="flex gap-2">
            <Button block color="default" onClick={onCancel}>
              取消
            </Button>
            <Button block color="primary" type="submit">
              保存
            </Button>
          </div>
        }
      >
        <Form.Item name="name" label="姓名" rules={[{ required: true }]}>
          <Input placeholder="请输入姓名"></Input>
        </Form.Item>
        <Form.Item name="phone" label="手机号" rules={[{ required: true }]}>
          <Input placeholder="请输入手机号" maxLength={11}></Input>
        </Form.Item>
        <Form.Item
          label="地址"
          name="address"
          rules={[{ required: true }]}
          onClick={() => setVisible(true)}
        >
          <Input value={data?.address} placeholder="请选择" readOnly></Input>
        </Form.Item>
        <Form.Item
          name="detailAdd"
          label="详细地址"
          rules={[{ required: true }]}
        >
          <Input placeholder="请输入详细地址"></Input>
        </Form.Item>
      </Form>
      <Cascader
        options={cascaderOptions}
        visible={visible}
        value={data?.addressCode}
        onSelect={(v, e) => {
          console.log(e);
        }}
        onConfirm={(val, extend) => {
          handleConfirm(val as string[], extend.items as Items);
        }}
        onClose={() => setVisible(false)}
      ></Cascader>
    </div>
  );
}
